package com.siyoumi.aspect;

import com.siyoumi.annotation.RequestLimit;
import com.siyoumi.component.XRedis;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.exception.EnumSys;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

//限请求数
@Slf4j
@Aspect
@Component
public class AspectRequestLimit {
    protected String getRedisKey(String fix) {
        return "RequestLimit:" + fix;
    }

    @Around("@annotation(requestLimit)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint, RequestLimit requestLimit) throws Throwable {
        log.debug("{}秒，请求上限{}次", requestLimit.second(), requestLimit.limit());

        RequestLimitGetKey func = (RequestLimitGetKey) XSpringContext.getBean(requestLimit.key());
        String key = func.getKey(proceedingJoinPoint);
        String redisKey = getRedisKey(key);
        log.debug("key: {}", key);
        log.debug("redis_key: {}", redisKey);

        Boolean pass = XRedis.getBean().increment(redisKey, requestLimit.limit(), requestLimit.second());
        if (!pass) {
            return EnumSys.LIMIT_MAX_ERROR.getR();
        }

        return proceedingJoinPoint.proceed();
    }
}
